<template>
	<view class="">
		<NavBar title="销售数据" :isShowLeftBtn="true">
		</NavBar>
	</view>
	<view class="content" :style="{minHeight:contentHeight}">
		<view class="condition_box flex_both m_b_44">
			<view class="condition_calendar flex_both" style="width: 92rpx; padding: 0 22rpx;"
				@click="showPicker('year')">
				<text class="f_24_0">
					{{searchForm.year}}
				</text>
				<view class="">
					<up-icon name="arrow-down-fill" color="#C2C2C2" size="11"></up-icon>
				</view>
			</view>
			<view class="m_l_18 m_r_18">
				<text class="f_24_0">
					年
				</text>
			</view>
			<view class="condition_calendar flex_both" style="width: 78rpx;padding: 0 22rpx;"
				@click="showPicker('month')">
				<text class="f_24_0">
					{{searchForm.month}}
				</text>
				<view class="">
					<up-icon name="arrow-down-fill" color="#C2C2C2" size="11"></up-icon>
				</view>
			</view>
			<view class="m_l_18 m_r_18">
				<text class="f_24_0">
					月
				</text>
			</view>
			<view class="condition_calendar flex_both" style="width: 78rpx;padding: 0 22rpx;"
				@click="showPicker('day')">
				<text class="f_24_0">
					{{searchForm.day}}
				</text>
				<view class="">
					<up-icon name="arrow-down-fill" color="#C2C2C2" size="11"></up-icon>
				</view>
			</view>
			<view class="m_l_18 m_r_18">
				<text class="f_24_0">
					日
				</text>
			</view>
			<view class="condition_btn" @click="onSearch">
				<text class="f_26_f">
					搜索
				</text>
			</view>
		</view>
		<view class="main">
			<view class="main_header flex_both">
				<view class="" style="width: 450rpx;">
					<text class="f_28_0_b u-line-1">
						XXX洗车店 — 销售数据
					</text>
				</view>
				<view class="main_header_btn" @click="exportExcel">
					<view class="m_b_10">
						<text class="f_24_f" style="color: #F94219;">
							导出数据
						</text>
					</view>
				</view>
			</view>
			<view class="table_header flex">
				<view class="table_header_col table_header_col1">
					<text class="f_26_0">
						序号
					</text>
				</view>
				<view class="table_header_col table_header_col2">
					<text class="f_26_0">
						日期
					</text>
				</view>
				<view class="table_header_col table_header_col3">
					<text class="f_26_0">
						销售额
					</text>
				</view>
			</view>
			<scroll-view scroll-y="true" :style="{height: viewHeight }" :refresher-threshold="100"
				@scrolltolower="scrolltolowerFun" refresher-enabled="true" refresher-default-style="none">
				<view class="main_list">
					<view class="table_content">
						<view class="main_item table_content_row flex" v-for="(item,index) in dataList">
							<view class="table_content_row_col table_content_row_col1">
								<text class="f_24_0 u-line-1">
									{{index + 1}}
								</text>
							</view>
							<view class="table_content_row_col table_content_row_col2">
								<text class="f_24_0 u-line-1">
									{{item.date}}
								</text>
							</view>
							<view class="table_content_row_col table_content_row_col3">
								<text class="f_24_0 u-line-1">
									{{item.count}}次
								</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<up-picker :show="timeShow" :defaultIndex="timeDefaultIndex" keyName="label" :columns="timeColumns"
				@confirm="onTimeOk" @cancel="onTimeCancel"></up-picker>
		</view>
	</view>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import { onLoad, onShow } from "@dcloudio/uni-app";
	import NavBar from "@/components/navbar.vue"
	import * as XLSX from '@/common/excel.js'
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	const viewHeight = ref()
	const sId = ref(0)



	onLoad((e) => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 76}rpx)`
				viewHeight.value = `calc(100vh - ${statusBarHeight.value + 342}rpx)`
			}
		});
		sId.value = e.id
		initSearchForm()
		initTimeColumns1()
		initTimeColumns2()
		initTimeColumns3(new Date().getFullYear(), new Date().getMonth() + 1)
		childShopSale()
	})
	// const page = ref(1)
	// const loadShow = ref(false)
	// const loadMessage = ref('加载中')
	const scrolltolowerFun = () => {
		// page.value = ++page.value;
		// loadShow.value = true;
		// setTimeout(() => {
		// }, 1000)
	}
	// 检索条件
	const searchForm = ref({
		year: 2024,
		month: 1,
		day: 1
	})
	const timeShow = ref(false)
	const timeColumns = ref([[]])
	const timeDefaultIndex = ref([0])
	const timeColumns1 = ref([[]])
	const timeColumns2 = ref([[]])
	const timeColumns3 = ref([[]])
	const initTimeColumns1 = () => {
		let cYear = new Date().getFullYear()
		timeColumns1.value[0] = []
		for (let i = 0; i <= 50; i++) {
			timeColumns1.value[0].push({ label: cYear - i, index: i })
		}
	}
	const initTimeColumns2 = () => {
		timeColumns2.value[0] = [{ label: '全部' }]
		for (let i = 1; i <= 12; i++) {
			timeColumns2.value[0].push({ label: i })
		}
	}
	const initTimeColumns3 = (cYear, cMonth) => {
		timeColumns3.value[0] = [{ label: '全部' }]
		let count = getMonthDay(cYear, cMonth)
		for (let i = 1; i <= count; i++) {
			timeColumns3.value[0].push({ label: i })
		}
		if (searchForm.value.day > timeColumns3.value[0][timeColumns3.value[0].length - 1].label) {
			searchForm.value.day = timeColumns3.value[0][timeColumns3.value[0].length - 1].label
		}
	}
	// 获取某月多少天
	const getMonthDay = (year, month) => {
		let days = new Date(year, month, 0).getDate()
		return days
	}
	const activeType = ref('year')
	const showPicker = (e) => {
		activeType.value = e
		if (activeType.value == 'year') {
			timeColumns.value = timeColumns1.value
			timeDefaultIndex.value = [timeColumns1.value[0].filter(v => { return v.label == searchForm.value.year })[0].index]
		} else if (activeType.value == 'month') {
			timeColumns.value = timeColumns2.value
			setTimeout(() => {
				if (searchForm.value.month == '全部') {
					timeDefaultIndex.value = [0]
					return
				}
				timeDefaultIndex.value = [searchForm.value.month]
			})
		} else if (activeType.value == 'day') {
			if (searchForm.value.month == '全部') {
				return
			}
			timeColumns.value = timeColumns3.value
			setTimeout(() => {
				if (searchForm.value.day == '全部') {
					timeDefaultIndex.value = [0]
					return
				}
				timeDefaultIndex.value = [searchForm.value.day]
			})
		}
		timeShow.value = true
	}
	const onTimeOk = (e) => {
		if (activeType.value == 'year') {
			searchForm.value.year = e.value[0].label
			initTimeColumns3(searchForm.value.year, searchForm.value.month)
		} else if (activeType.value == 'month') {
			if (e.value[0].label == '全部') {
				searchForm.value.day = '全部'
			}
			searchForm.value.month = e.value[0].label
			initTimeColumns3(searchForm.value.year, searchForm.value.month)
		} else if (activeType.value == 'day') {

			searchForm.value.day = e.value[0].label
		}
		timeShow.value = false
	}
	const onTimeCancel = () => {
		timeShow.value = false
	}

	const initSearchForm = () => {
		let cTime = new Date()
		searchForm.value.year = cTime.getFullYear()
		searchForm.value.month = '全部'
		searchForm.value.day = '全部'
	}
	const dataList = ref([])
	const childShopSale = async () => {
		let month = ''
		let day = ''
		if (searchForm.value.month != '全部') {
			month = (searchForm.value.month > 9 ? searchForm.value.month : '0' + searchForm.value.month)
		}
		if (searchForm.value.day != '全部') {
			day = (searchForm.value.day > 9 ? searchForm.value.day : '0' + searchForm.value.day)
		}
		let res = await proxy.$http('my.childShopSale', {
			shop_id: sId.value,
			year: searchForm.value.year,
			month: month,
			day: day,
			is_export: 0
		})
		dataList.value = res.data
	}

	const onSearch = () => {
		dataList.value = []
		childShopSale()
	}

	const exportExcel = async () => {
		let month = ''
		let day = ''
		if (searchForm.value.month != '全部') {
			month = (searchForm.value.month > 9 ? searchForm.value.month : '0' + searchForm.value.month)
		}
		if (searchForm.value.day != '全部') {
			day = (searchForm.value.day > 9 ? searchForm.value.day : '0' + searchForm.value.day)
		}

		let res = await proxy.$http('my.childShopSale', {
			shop_id: sId.value,
			year: searchForm.value.year,
			month: month,
			day: day,
			is_export: 1
		})

		if (res.code == 1) {
			uni.downloadFile({
				url: res.data, //下载地址，后端接口获取的链接
				header: {
					'content-type': 'application/json',
				},
				success: (data) => {
					console.log(data.tempFilePath)
					console.log(JSON.stringify(data))
					if (data.statusCode === 200) {
						wx.getFileSystemManager().saveFile({
							tempFilePath: data.tempFilePath,
							success: function (res) {
								// 保存文件成功
								wx.openDocument({
									filePath: res.savedFilePath,
									showMenu: true,
								})
							},
							fail: function (error) {
								// 保存文件失败
								console.log(error)
							}
						})
					}
				},
				fail: (err) => {
					console.log(err);
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '失败请重新下载',
					});
				},
			});
		}

	}
	const handle_view_bom = () => {
		let month = ''
		let day = ''
		if (searchForm.value.month != '全部') {
			month = (searchForm.value.month > 9 ? searchForm.value.month : '0' + searchForm.value.month)
		}
		if (searchForm.value.day != '全部') {
			day = (searchForm.value.day > 9 ? searchForm.value.day : '0' + searchForm.value.day)
		}
		uni.showLoading({
			title: '打开中~'
		})
		uni.request({
			url: proxy.$config.baseUrl + "/Api/Shop/childShopSale",
			data: {
				shop_id: sId.value,
				year: searchForm.value.year,
				month: month,
				day: day,
				is_export: 1
			},
			method: 'POST',
			responseType: 'arraybuffer',
			header: {
				'system-type': 3,
				'Authorization': uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
			},
			success: (res) => {
				console.log(res);
				let file_name = '文件名'
				if (res && file_name) {
					// uni.saveFile({
					// 	tempFilePath: res.tempFilePath,//下载成功之后返回的临时路径
					// 	success: (e) => {
					// 		console.log(e);
					// 		//保存成功之后 打开文件
					// 		uni.openDocument({
					// 			filePath: e.savedFilePath,
					// 			fail: (e) => {
					// 				uni.showToast({
					// 					title: `打开失败` + e
					// 				})
					// 			}
					// 		})
					// 	},
					// 	fail: (e) => {
					// 		uni.showToast({
					// 			title: `保存失败` + e
					// 		})
					// 	}
					// })
					handle_open_binary(res, file_name)


				}
			},
			fail() {
				uni.hideLoading()
			}
		})
	}
	// const XLSX = require('xlsx');
	const handle_open_binary = (data_, fileName) => {
		const fs = uni.getFileSystemManager(); // 获取全局唯一的文件管理器
		// const fileName = !res.header['Content-Disposition']?'xxx文件':decodeURIComponent(res.header['Content-Disposition'].match(/filename="?(.+)"?/)[1]) //文件名
		let filepath = uni.env.USER_DATA_PATH + '/' + fileName + '.xlsx'
		fs.writeFile({ //写文件
			// uni.env.USER_DATA_PATH 是小程序提供的访问用户文件路径的变量
			filePath: filepath,
			data: data_.data,
			encoding: "binary", //二进制流文件必须是 binary
			success(e) {
				console.log(filepath);
				uni.saveFile({
					tempFilePath: filepath,
					filePath: filepath,//下载成功之后返回的临时路径
					success: (e) => {
						//保存成功之后 打开文件
						uni.openDocument({
							filePath: e.savedFilePath,
							fail: (e) => {
								uni.showToast({
									title: `打开失败` + e
								})
							}
						})
					},
					fail: (e) => {
						console.log(e);
						uni.showToast({
							title: `保存失败` + e
						})
					}
				})
				// //下载文件
				// uni.downloadFile({//只能是GET请求
				// 	url: filepath,//请求地址
				// 	header: {
				// 		'Authorization': uni.getStorageSync('Authorization')//请求头。
				// 	},
				// 	success: (res) => {
				// 		console.log(res);
				// 		wx.getFileSystemManager().readdir({
				// 			dirPath:wx.env.USER_DATA_PATH,
				// 			success:(res2)=>{
				// 				console.log('dir','http://tmp/'+res2.files[1])
				// 			}
				// 		})

				// 		//下载成功
				// 		if (res.statusCode === 200) {
				// 			//保存文件
				// 			uni.saveFile({
				// 				tempFilePath: res.tempFilePath,//下载成功之后返回的临时路径
				// 				success: (e) => {
				// 					//保存成功之后 打开文件
				// 					uni.openDocument({
				// 						filePath: e.savedFilePath,
				// 						fail: (e) => {
				// 							uni.showToast({
				// 								title: `打开失败` + e
				// 							})
				// 						}
				// 					})
				// 				},
				// 				fail: (e) => {
				// 					console.log(e);
				// 					uni.showToast({
				// 						title: `保存失败` + e
				// 					})
				// 				}
				// 			})
				// 		}
				// 	},
				// 	fail: (e) => {
				// 		this.isDownloading = false
				// 		uni.showToast({
				// 			title: `文件下载失败` + e,
				// 			icon: "none",
				// 		})
				// 	}
				// });

				// uni.openDocument({ // 打开文档
				// 	filePath: filepath, // 上面存入的文件路径
				// 	showMenu: true, // 显示右上角菜单
				// 	fileType: 'xlsx',
				// 	success: function (res2) {
				// 		uni.hideLoading()
				// 	},
				// 	fail: (err) => {
				// 		console.error(err)
				// 		uni.hideLoading()
				// 		uni.showToast({
				// 			title: err.errMsg,
				// 			icon: "none"
				// 		})
				// 	}
				// })
			},
			fail: function (err) {
				console.error(err)
				uni.showToast({
					title: err.errMsg,
					icon: "none"
				})
				uni.hideLoading()
			}
		})
	}
</script>
<style lang="scss" scoped>
	.content {
		background: #F7F8FC;
		padding: 20rpx;
		padding-bottom: 64rpx;

		.condition_box {
			.condition_calendar {
				height: 63rpx;
				background: #FFFFFF;
				box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
				border-radius: 10rpx;
			}

			.condition_btn {
				width: 119rpx;
				height: 63rpx;
				background: linear-gradient(90deg, #F93E19, #F75C1B);
				box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.main {
			background: #FFFFFF;
			box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
			border-radius: 10rpx;

			.main_header {
				height: 78rpx;
				padding: 0 24rpx;

				.main_header_btn {
					width: 133rpx;
					height: 47rpx;
					background: #FFFFFF;
					border-radius: 5rpx;
					border: 2rpx solid #F74A1B;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.table_header {
				height: 78rpx;
				background: #E4E3E3;

				.table_header_col {
					flex-shrink: 0;
					height: 78rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.table_header_col1,
				.table_header_col2 {
					border-right: 2rpx solid #F3F3F1;
				}

				.table_header_col1 {
					width: 158rpx;
				}

				.table_header_col2 {
					width: 270rpx;
				}

				.table_header_col3 {
					width: 282rpx;
				}
			}

			.table_content {
				.table_content_row {
					.table_content_row_col {
						flex-shrink: 0;
						height: 60rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}

					.table_content_row_col1,
					.table_content_row_col2 {
						border-right: 2rpx solid #F3F3F1;
					}

					&:not(:nth-last-child(1)) {
						border-bottom: 2rpx solid #F3F3F1;
					}

					.table_content_row_col1 {
						width: 158rpx;
					}

					.table_content_row_col2 {
						width: 270rpx;
					}

					.table_content_row_col3 {
						width: 282rpx;
					}
				}
			}

		}
	}
</style>